<?php 
namespace Admin\Model;
use Think\Model;
/**
 * create table art_accessrole(
    -> role_id INT(8) NOT NULL,
    -> access_id INT(8) NOT NULL,
    -> uptime INT(20) NOT NULL,
    -> FOREIGN KEY(role_id) REFERENCES art_role(id) ON UPDATE CASCADE ON DELETE RESTRICT,
    -> FOREIGN KEY(access_id) REFERENCES art_access(id) ON UPDATE CASCADE ON DELETE RESTRICT,
    -> PRIMARY KEY(role_id, access_id));
*/
class AccessroleModel extends Model{
    private $_role_id;
    private $_access_id;
    private $_uptime;
	public function allot($rid, $accesses){
        $this->_role_id = $rid;
        $now = $this->getByRole();
        foreach($accesses as $access){
            $this->_access_id = $access;
            $this->addOne();
        }
        foreach($now as $access){
            if(!in_array($access['access_id'], $accesses)){
                $this->_access_id = $access['access_id'];
                $this->deleteOne();
            }
        }
        $accessroles = $this->select();
        S('accessroles', $accessroles);
    }
    
    public function hasPermission($node, $type, $rid){
        $Access = D('Access');
        $acc = $Access->where(array('name'=>$node))->find();
        if($acc == null){
            return false;
        }
        if($this->where(array('access_id'=>$acc['id'], 'role_id'=>$rid))->find()!==null){
            return true;
        }else{
            return false;
        }
    }
    
    public function getList(){  // 获取数据列表，根据角色排列
        $roles = $this->group('role_id')->select();
        $res = array();
        foreach($roles as $role){
            $res[$role['role_id']] = $this->where(array('role_id'=>$role['role_id']))->select();
        }
        return $res;
    }
    
    public function getByRole(){
        return $this->where(array('role_id'=>$this->_role_id))->select();
    }
    
    private function addOne(){
        if(!$this->isHas()){
            $data = array();
            $data['role_id'] = $this->_role_id;
            $data['access_id'] = $this->_access_id;
            $data['uptime'] = time();
            return $this->add($data);
        }
        return false;
    }
    
    private function isHas(){
        if($this->where(array('role_id'=>$this->_role_id, 'access_id'=>$this->_access_id))->find() == null){
            // 数据不存在
            return false;
        }
        return true;
    }
    
    private function deleteOne(){
        $data = array();
        $data['role_id'] = $this->_role_id;
        $data['access_id'] = $this->_access_id;
        return $this->where($data)->delete();
    }
}